import os
import pandas as pd
import utils

from DresssenceModel import *

process_logger = utils.process_logger


@process_logger
def createColorMedium(color_pd, ColorMedium):
    """
    清除现有ColorMedium对象，根据源文件创建ColorMedium对象，存入数据库中

    Args:
        color_pd ([pd.DataFrame]): [description]
    """
    color_medium = color_pd["color_medium"].dropna().to_list()

    color_medium = [
        item
        for i, item in enumerate(color_medium)
        if i == color_medium.index(item)
    ]

    color_medium = [
        {"id": i, "name": hi, "color_tag": "255-255-255"}
        for (i, hi) in enumerate(color_medium)
    ]

    ColorMedium.insert_many(color_medium).execute()


@process_logger
def createColorBasic(color_pd, ColorBasic, ColorMedium):
    """
    清除现有ColorBasic对象，根据源文件创建ColorBasic对象，存入数据库中

    Args:
        color_pd ([pd.DataFrame]): [description]
    """
    # 根据字典特性，创建唯一的ColorBasic:ColorMedium对
    basic_medium = {
        basic: medium
        for (basic, medium) in zip(
            color_pd["color_basic"].dropna(),
            color_pd["color_medium"].dropna(),
        )
    }

    color_basic = [
        {
            "id": i,
            "name": item[0],
            "color_tag": "255-255-255",
            "color_medium": ColorMedium.get(name=item[1]),
        }
        for (i, item) in enumerate(basic_medium.items())
    ]

    ColorBasic.insert_many(color_basic).execute()


@process_logger
def createColor(color_pd, Color, ColorBasic):
    """
    清除现有Color对象，根据源文件创建Color对象，存入数据库中

    Args:
        color_pd ([pd.DataFrame]): [description]
    """
    # 建立hlc与rgb字典
    hlc_rgb = {
        hlc: rgb
        for (hlc, rgb) in zip(color_pd.color_hlc, color_pd.color_rgb)
    }
    colors = []
    # 建立ColorBasic.name与ColorBasic字典
    color_basic = {item.name: item for item in ColorBasic.select()}
    # 遍历非'c'（汉字）打头的列，将列中的hlc创建为属于列名对应的ColorBasic的Color
    count = 0
    for (i, column) in enumerate(
        list(
            filter(
                lambda x: not x.startswith("c"),
                color_pd.columns.to_list(),
            )
        )
    ):
        for (j, col) in enumerate(color_pd[column].dropna()):
            count += 1
            colors.append(
                {
                    "id": count,
                    "hlc": col,
                    "rgb": hlc_rgb[col],
                    "color_basic": color_basic[column],
                }
            )
    Color.insert_many(colors).execute()


@process_logger
def tidingColor(Color, ColorBasic, ColorMedium, isOld):
    """
    依次根据其属性对ColorBasic、ColorMedium、ColorHigher求取色彩平均值，并更新其数据库字段
    """
    for bas in ColorBasic.select():
        if isOld:
            colors = bas.oldcolor_set
        else:
            colors = bas.color_set

        if len(colors):
            r, g, b = [], [], []
            for color in colors:
                rgb = color.rgb.split("-")
                r.append(int(rgb[0]))
                g.append(int(rgb[1]))
                b.append(int(rgb[2]))
            r, g, b = (
                sum(r) // len(r),
                sum(g) // len(g),
                sum(b) // len(b),
            )
            bas.color_tag = "-".join([str(r), str(g), str(b)])
        bas.save()
    for med in ColorMedium.select():
        if isOld:
            basics = med.oldcolorbasic_set
        else:
            basics = med.colorbasic_set

        r, g, b = [], [], []
        for basic in basics:
            rgb = basic.color_tag.split("-")
            r.append(int(rgb[0]))
            g.append(int(rgb[1]))
            b.append(int(rgb[2]))
        r, g, b = sum(r) // len(r), sum(g) // len(g), sum(b) // len(b)
        # print("-".join([str(r), str(g), str(b)]))
        med.color_tag = "-".join([str(r), str(g), str(b)])
        med.save()


def createColors(isOld=False):
    """
    清除四张数据表
    """
    color, color_basic, color_medium = Color, ColorBasic, ColorMedium
    if os.path.exists("extractedColorData.xlsx"):
        color_pd = pd.read_excel("extractedColorData.xlsx")
    else:
        color_pd = pd.read_excel("OldColorDataSource.xlsx")
    if isOld:
        color, color_basic, color_medium = (
            OldColor,
            OldColorBasic,
            OldColorMedium,
        )
        color_pd = pd.read_excel("OldColorDataSource.xlsx")
    color.delete().execute()
    color_basic.delete().execute()
    color_medium.delete().execute()
    createColorMedium(color_pd, color_medium)
    createColorBasic(color_pd, color_basic, color_medium)
    createColor(color_pd, color, color_basic)
    tidingColor(color, color_basic, color_medium, isOld)


def main():
    createColors()


if __name__ == "__main__":
    main()